import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateProductDto } from './dto/product.dto';
import { Product } from './entities/product.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PaginationDto, PaginatedResponseDto } from '../common/dto/pagination.dto';

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
  ) {}

  async create(createProductDto: CreateProductDto): Promise<Product> {
    const product = this.productRepository.create(createProductDto);
    return this.productRepository.save(product);
  }

  async findAll(): Promise<Product[]> {
    return this.productRepository.find();
  }

  async findAllPaginated(paginationDto: PaginationDto): Promise<PaginatedResponseDto<Product>> {
    const { page = 1, limit = 10 } = paginationDto;
    const skip = (page - 1) * limit;

    const [items, total] = await this.productRepository.findAndCount({
      skip,
      take: limit,
      order: {
        id: 'DESC', // 默认按ID降序排序
      },
    });

    const totalPages = Math.ceil(total / limit);

    return {
      items,
      total,
      totalPages,
      currentPage: page,
      limit,
    };
  }

  async findOne(id: number): Promise<Product> {
    const product = await this.productRepository.findOne({ where: { id } }); // 使用对象形式查找
    if (!product) {
      throw new NotFoundException(`Product with ID ${id} not found`);
    }
    return product;
  }

  async findRecommendedProducts(): Promise<Product[]> {
    return this.productRepository.find({
      where: { isRecommended: true },
      order: { sales: 'DESC' }, // 根据销量降序排序
    });
  }

  async findRecommendedProductsPaginated(paginationDto: PaginationDto): Promise<PaginatedResponseDto<Product>> {
    const { page = 1, limit = 10 } = paginationDto;
    const skip = (page - 1) * limit;

    const [items, total] = await this.productRepository.findAndCount({
      where: { isRecommended: true },
      order: { sales: 'DESC' }, // 根据销量降序排序
      skip,
      take: limit,
    });

    const totalPages = Math.ceil(total / limit);

    return {
      items,
      total,
      totalPages,
      currentPage: page,
      limit,
    };
  }

  async remove(id: number): Promise<void> {
    const product = await this.findOne(id);
    if (!product) {
      throw new NotFoundException(`Product with ID ${id} not found`);
    }
    await this.productRepository.remove(product);
  }
}